import { cloneDeep } from "lodash";
import { AxiosResponse } from "axios";
import { BaseResponse, request } from "../util/index";
import { PermissionRecord } from "src/views/role/RoleType";
import { PipelineStage } from "mongoose";

export const uplodaImage = async (formData: FormData) => {
	const result = await request.post("/admin/upload/image", formData);
	return result.data;
};
export const uplodaImages = async (formData: FormData) => {
	const result = await request.post("/admin/upload/images", formData);
	return result.data;
};
export interface GetSourceParams extends Record<string, unknown> {
	__fields__?: string;
	page?: number;
	pageSize?: number;
	source: string;
	lookup?: PipelineStage.Lookup['$lookup'];
}
export const getSource = async <R = BaseResponse<unknown>, P = GetSourceParams>(params: GetSourceParams) => {
	const { source, ...remainingParams } = params;
	const query = cloneDeep(remainingParams);
	for (const key in query) {
		const element = query[key];
		if (Object.prototype.toString.call(element) === "[object Object]") {
			query[key] = JSON.stringify(element);
		}
	}
	const { data } = await request.get<BaseResponse<R>, AxiosResponse<BaseResponse<R>, P>, P>(`/admin/source/${source}`, {
		params: query,
	});
	return data;
};

export const createSource = async <R = Record<string, unknown>>(props: { source: string } & R) => {
	const { source, ...data } = props;
	const { data: result } = await request.post<BaseResponse<null>, AxiosResponse<BaseResponse<null>>>(`/admin/source/${source}`, data);
	return result;
};
export const updateSource = async <R = Record<string, unknown>>(props: { source: string; id: string } & R) => {
	const { source, ...data } = props;
	const { data: result } = await request.patch<BaseResponse<null>, AxiosResponse<BaseResponse<null>>>(`/admin/source/${source}`, data);
	return result;
};
export const deleteSource = async (props: { id: string; source: string }) => {
	const { id, source } = props;
	const { data: result } = await request.delete(`/admin/source/${source}`, { data: { id } });
	return result;
};
export const getMenu = async () => {
	const result = await request.get("/admin/menu/list");
	return result.data;
};
export const getMenuAndRoutes = async () => {
	const result = await request.get<BaseResponse<PermissionRecord[]>>("admin/menu/menusAndRoutes");
	return result.data;
};
